package com.atguigu.cart.interceptor;

import com.atguigu.cart.vo.UserInfoDTO;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.vo.MemberResponseVO;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/16 15:08 周一
 * @description : 在执行目标方法之前 判断用户的登录状态。并封装传递给controller目标请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoDTO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        目标方法执行之前
         */

        UserInfoDTO userInfoDTO = new UserInfoDTO();
        HttpSession session = request.getSession();
        MemberResponseVO member = (MemberResponseVO) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            // 用户登录
            userInfoDTO.setUserId(member.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (Func.isNotEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equalsIgnoreCase(name)) {
                    userInfoDTO.setUserKey(cookie.getValue());
                    userInfoDTO.setTempUser(true);
                }
            }
        }

        if (Func.isEmpty(userInfoDTO.getUserKey())) {
            String uuid = Func.randomUUID();
            userInfoDTO.setUserKey(uuid);
        }

        threadLocal.set(userInfoDTO);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoDTO userInfo = threadLocal.get();

        if (!userInfo.getTempUser()) {
            // 持续的延长用户的过期时间
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
